﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DbfViewer.Commands;
using DbfViewer.Views;
using System.Data;
using DbfViewer.Models;
using System.Collections.ObjectModel;
using System.Windows.Input;
using DbfViewer.Models.DataTypes;

namespace DbfViewer.ViewModels
{
	public class TableEditViewModel : ViewModelBase
	{
		protected IDbfFile DbfFile { get; set; }

		public TableEditViewModel(IDbfFile dbfFile)
		{
			DbfFile = dbfFile;
		}

		private string viewTitle = "Редактирование таблицы";
		public string ViewTitle
		{
			get 
			{ 
				return viewTitle; 
			}
			set
			{
				viewTitle = value;
				OnPropertyChanged("ViewTitle");
			}
		}

		private DelegateCommand addCommand;
		public ICommand AddCommand
		{
			get { return addCommand ?? (addCommand = new DelegateCommand(Add, CanExecute)); }
		}
		private void Add()
		{
			AddFieldViewModel model = new AddFieldViewModel();
			AddFieldView view = new AddFieldView() { DataContext = model };
			if (view.ShowDialog().Value)
			{
				var column = new DataColumn(model.Name.ToLower(), model.SelectedValue.Type);
				DbfFile.AddField(column);
				OnPropertyChanged("Fields");
			}
		}
		private bool CanExecute()
		{
			return fields != null;
		}


		private DbfField selectedField = null;
		public DbfField SelectedField
		{
			get { return selectedField; }
			set
			{
				selectedField = value;
				OnPropertyChanged("SelectedField");
			}
		}
		private ObservableCollection<DbfField> fields = new ObservableCollection<DbfField>();
		public ObservableCollection<DbfField> Fields
		{
			get
			{
				if (fields.Count != DbfFile.Table.Columns.Count)
				{
					fields.Clear();
					foreach (DataColumn column in DbfFile.Table.Columns)
					{
						var field = new DbfField();
						field.Name = column.ColumnName;
						field.Type = DbfHelper.GetDbfType(column.DataType);
						fields.Add(field);
					}
				}
				return fields;
			}
			set
			{
				fields = value;
				OnPropertyChanged("Fields");
			}
		}
	}
}
